layui.config({
	base: '/static/layui_extends/'
	,version: enianAdmin.config('cacheVersion')
})
layui.use(['element', 'layer', 'enian_menu', 'laytpl','mouseRightMenu','enianWindow'], function() {
	var form = layui.form,
		layer = layui.layer,
		$ = layui.$,
		jq = layui.jquery,
		menu_left = layui.enian_menu,
		laytpl = layui.laytpl,
		element = layui.element,
		temp=new Date().getTime(),
		enianWindow = layui.enianWindow,
		mouseRightMenu = layui.mouseRightMenu;

	// 初始化窗口模块-为了适配全局主题，此代码应放在加载主题前
	enianWindow.init({
		taskBtns:{
			left:[
			  	// ['sun','<i class="iconfont icon-win"></i>']
	  		],
	  		right:[
				['min-all','<i class="iconfont icon-zuixiao"  title="缩小化所有"></i>']
	  		]
		},
	    cssConfig:{
	        iframe_theme_color :'#009688',
	       iframe_text_color : 'white'
	       ,iframe_text_hover_background : '#2d527e'
	       ,task_bar_project_color : '#cecece'
	       ,task_bar_project_selected_color :'white'
	    },
	    taskBtnsClick:function(className){
	      if(className == 'min-all'){
	        var list = enianWindow.windowsList();
	        for (var i = 0; i < list['item'].length; i++) {
	          enianWindow.min(list['item'][i]);
	        }
	      }
		},
		success:function(o,i){
			enianWindow.taskBarBtnMoveDisplay(false);	//隐藏窗口模块状态栏移动按钮
			enianWindow.setWindowSize(i,'calc(100% - 35px)',0,'35px','100%'); //由于各种原因窗口不能自动左边为0，需加载成功后手动设置尺寸
			enianWindow.taskDisplay(false);	//隐藏窗口

		}

	});
	

	//----左侧菜单----start
	var data = $data;
	for (var i = 0; i < data.length; i++) {
		if(data[i].pid==0 && i==0){
			data[i]['open']=true;
		}
		data[i].img = data[i].img == '' ? '' : '<i class="layui-icon ' + data[i].img + ' "></i>';
	}
	//渲染左侧菜单并监听菜单点击
	menu_left.reader(data, '#menu_left', function(obj) {
		var url = obj.url;
		if(url == window.location.pathname) {
			//刷新功能
			loadpage(1, {
				'url': url
			});
		} else {
			if(obj.type == 0) {
				loadpage(4, {
					'url': url
				});
			} else {
				window.open(url);
			}
		}
		//储存菜单设置项
//		layui.data('enian_menu', {
//		  key: 'nowMenu'+temp
//		  ,value: url
//		});
	})
	
	//----左侧菜单---- end
	
	enianAdminListen();//监听enianAdmin.listen集
	init();//初始化函数（页面所有代码执行完成执行此函数）
	
	//加载主题文件，如果名称为空，将不使用主题文件，
	var user_config = layui.data('user_config');
	if(user_config.theme) {
		enianAdmin.extend('updateTheme',user_config.theme);
	}
	
	
	
	$('body').removeClass('layui-hide');//主题文件加载完成显示body
	
	//首次加载子页面
	var arg = {
		'url': window.location.href
	};
	loadpage(0, arg);
	if(!menu_left.setCheck('url', window.location.pathname)){
//		layer.msg('没有菜单，读取默认菜单')
//		console.log(layui.data('enian_menu')['nowMenu'+temp])
//		menu_left.setCheck('url', layui.data('enian_menu')['nowMenu'+temp]);
		
	}
	
	

	

	//监听浏览器切换页面
	sapp.browserListen(null, function(obj) {
		var argObj = {
			'url': obj.state.url
		};
		loadpage(5, argObj)
		menu_left.setCheck('url', obj.state.url);
		return false;//阻止默认事件
	})

	
	//加载页面（页面加载前要做的事）
	function loadpage(type, argObj) {
		sapp.config({
			elem:'.son-page-body'
		})
		if(argObj.url != '') {
			//清空导航栏
			$('#enian_nav_bar_root').html('')
			//如果是-1则返回
			if(argObj.url == -1) {
				window.history.go(-1);
				return;
			}
			if(type == 0 || type == 5 || type == 1) {
				refreshTrun()
				sapp.render({
					subpageObj:argObj
					,done:function(resultObj){
						loadState(resultObj, type)
					}
				})
			} else {
				refreshTrun()
				sapp.render({
					subpageObj:argObj
					,updateUrlBar:true
					,done:function(resultObj){
						loadState(resultObj, type)
					}
				})
			}
		} else {
			console.warn('网址为空，不进行跳转')
		}

	}

	// 页面加载状态（包括浏览器跳转和页面跳转）/页面加载完成
	function loadState(obj, type) {
		//0,首页  1,子页刷新(或者菜单点中项与当前页面地址相同)  2,子页跳转  3,导航栏  4，菜单  5,浏览器切换
		refreshStop()
		if(obj.code != 0) {
			enian_nav_bar_Render()
			// 返回json对象
			if(obj.code == 2) {
				
				if(obj.json.code == 404) {
					sapp.partLoad({
						url:enianAdmin.config('path').errtpl + "/404.html"
					})
				} else {
					sapp.partLoad({
						url:enianAdmin.config('path').errtpl + "/accident.html"
						,done:function(r){
							$('#data-error-msg').html(obj.json.msg)
						}
					})
				}
			}
		} else if(!obj.code) {
			var content = "页面加载失败，错误码："+obj.errmsg.status;
			sapp.partLoad({
				url:enianAdmin.config('path').errtpl + "/error.html"
				,done:function(r){
					$('#data-error-msg').html(content)
				}
			})
			layer.alert(content);
		}
	}

	//渲染状态栏
	//type参数为空，在网页结构中获取内容
	function enian_nav_bar_Render(type, data) {
		var html = '';
		if(type == 1) {
			//JSON渲染
			$.each(data, function(i, k) {
				if(k['type'] == 'menu') {
					if(k.url) {
						menu_left.setCheck('url', k.url)
					} else {
						menu_left.setCheck('title', k.title)
					}

				} else if(k['type'] == 'url') {
					if(i == data.length - 1) {
						html += '<a data-url="' + k.url + '" style="cursor:default;font-size:17px;color:#666 ;" >' + k.title + '</a>'
					} else {
						html += '<a data-url="' + k.url + '" >' + k.title + '</a>'
					}
				}
			});
		} else {
			//DOM渲染
			var enian_bar_html = $('#enian-nav-bar a');

			//系统使用
			if(enian_bar_html.length > 0) {
				for(var i = 0; i < enian_bar_html.length; i++) {
					var h_this = $(enian_bar_html[i]);
					if(h_this.attr('type') == 'menu') {
						//设置左侧选中菜单
						if(h_this.data.title) {
							menu_left.setCheck('url', h_this.data.url)
						} else {
							menu_left.setCheck('url', h_this.data.title)
						}
					} else {
						if(i == enian_bar_html.length - 1) {
							html += '<a data-url="' + h_this.data("url") + '" style="cursor:default;font-size:17px;color:#666 ;" >' + h_this.html() + '</a>'
						} else {
							html += '<a data-url="' + h_this.data("url") + '" >' + h_this.html() + '</a>'
						}
					}

				}

			} else {

			}

		}
		if(html) {
			$('#enian_nav_bar_root').html('<span class="layui-breadcrumb">' + html + '</span>')
			element.render()
			//监听
			$('#enian_nav_bar_root .layui-breadcrumb a').click(function() {
				var arg = {
					'url': $(this).data('url')
				};
				loadpage(3, arg);
			})
		}
	}

	//监听右上角菜单点击
	$("#admin_name").click(function() {
		layer.open({
			type: 1,
			title: false, //不显示标题栏
			closeBtn: false,
			area: '300px;',
			shade: 0.8,
			id: 'quit_menu', //设定一个id，防止重复弹出
			btn: ['返回'],
			btnAlign: 'c',
			moveType: 1, //拖拽模式，0或者1
			content: $('#tpl-right-top-menu').html(),
			success: function(e, i) {
				//利用sessionData特性
				layui.sessionData('layer_index', {
					key: 'user_right_menu',
					value: i
				});
				layui.sessionData('layer_index').user_right_menu;
			}
		});
	})

	//监听-左侧菜单滑动特效
	$('#btn_hide_menu').click(function() {
		//$('#hd').attr('class','right_YD');
		if($('.menu_left').css('left') == '0px') {
			$(this).removeClass('layui-icon-spread-right')
			$(this).addClass('layui-icon-spread-left')
			$('.menu_left').css('left', '-200px');
			$('.layui-body').css('left', '0');
//			$('.nav-head').css('width','100%');
		} else {
			$(this).removeClass('layui-icon-spread-left')
			$(this).addClass('layui-icon-spread-right')
			$('.menu_left').css('left', '0px');
			$('.layui-body').css('left', '200px');
//			$('.nav-head').css('width','calc(100% - 200px)');
		}
	})

	//监听导航栏-刷新按钮
	$('#btn_nav_refresh').click(function() {
		refreshTrun()
		enianAdmin.reload();
	})

	//监听导航栏-返回按钮
	$('#btn_nav_back').click(function() {
		window.history.go(-1);
	})
	
	//刷新按钮开始转
	function refreshTrun(){
		$('#btn_nav_refresh').removeClass('layui-icon-refresh-3');
		$('#btn_nav_refresh').addClass('layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop');
	}
	
	//刷新按钮停止转
	function refreshStop(){
		$('#btn_nav_refresh').removeClass('layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop');
		$('#btn_nav_refresh').addClass('layui-icon-refresh-3');
	}

	//获取字符串右侧所有字符串
	function getStrR(sign, obj) {
		var index = obj.lastIndexOf(sign);
		obj = obj.substring(index + sign.length, obj.length);
		return obj;
	}

	//监听左侧菜单菜单右键
	$("#menu_left a").bind("contextmenu", function() {
		if(!$(this).data("url")){
			return false;	
		}
		var data = {'url':$(this).data("url"),'title':$(this).data("title")};
		var menu_data=[
			{'data':data,'type':0,'title':'窗口打开'},
			{'data':data,'type':1,'title':'浏览器新页打开'},
		]
		
		mouseRightMenu.open(menu_data,{shade: [0.2, '#393D49']},function(d){
			if(d.type == 0) {
				var url = enianAdmin.url(d.data.url);
				var param = url.params;
				var newUrl ='?PAGE_TYPE=2';
				for (var k in param) {
					newUrl+='&'+k+'='+param[k];
				}
				enianAdmin.openWindow({
				  	url: url.path+newUrl,
					title: d.data.title,
				  	area:['700px', '500px']
				 })
			}else{
				window.open(d.data.url);
			}
			//return false;//阻止默认事件（关闭菜单）
		})

		return false;//阻止默认浏览器事件
	})

	
	
	//enianAdmin.listen - 监听集
	function enianAdminListen(){
		//监听子页跳转页面
		enianAdmin.listen('go', function(obj) {
			var arg = {
				'url': obj.url
			};
			loadpage(2, arg);
		})
	
		//监听子页刷新页面
		enianAdmin.listen('reload', function() {
			var arg = {
				'url': window.location.href
			};
			loadpage(1, arg);
		})
	
		//监听渲染状态栏
		enianAdmin.listen('render_nav_bar', function(obj) {
			enian_nav_bar_Render(1, obj)
		})
	
		//监听右上角弹出的按钮
		enianAdmin.listen('user-menu-btn-click', function(obj) {
			layer.close(layui.sessionData('layer_index').user_right_menu);
			if(obj.name == "menu-left-set") {
				//enianAdmin.go('{:url("index/setMenuLeft")}');
				enianAdmin.go("/index/setMenuLeft");
			}
			if(obj.name == "about") {
				enianAdmin.go("/index/about");
			}
			if(obj.name == "updatepwd") {
				enianAdmin.go("/index/updatePassword");
			}
		})

		// enianAdmin 进行二次封装 enianWindow的open方法
		enianAdmin.openWindow = function(obj){

			enianWindow.open({
				 url: obj.url,
				 title:obj.title,
				 area:obj.area || ['700px', '500px'],
				 end:function(){
				 	var w_list = enianWindow.windowsList();
				 	if(w_list.item.length == 0){
				 		// 状态栏隐藏，铺满文档
				 		enianWindow.taskDisplay(false);
				 		$('body .layui-layout .center-body').css('height','100%');
						$('body .layui-layout .layui-side').css('height','100%');
				 	}
				 	if(obj.end){
				 		obj.end()
				 	}
				 },
				 success:function(layero,index){
				 	var w_list = enianWindow.windowsList();
				 	if(w_list.item.length == 1){
				 		// 留空给状态栏
				 		enianWindow.taskDisplay(true);
				 		var height = "calc(100% - 35px)";
						$('body .layui-layout .center-body').css('height',height);
						$('body .layui-layout .layui-side').css('height',height);				 		
				 	}
				 	// 监听任务栏项目右键被单击
					$("#iframe-task-obj"+index).bind("contextmenu",function(){
						var arg = {"index":index};
						var menu_data=[
					            {'data':arg,'type':1,'title':'窗口移动到可视区'}
					            ,{'data':arg,'type':2,'title':'关闭其他窗口'}
					            ,{'data':arg,'type':3,'title':'关闭所有窗口'}

					        ]
						
						mouseRightMenu.open(menu_data,{shade: [0.2, '#393D49']},function(active){
				            switch(active.type){
				            	case 1:
				            		enianWindow.setWindowSize(index,100,100,400,500);
				            		break;
				            	case 2:
				            		var window_list = enianWindow.windowsList();
				            		for (var i in  window_list['item']) {
				            			if(window_list['item'][i] != index){
				            				enianWindow.close(window_list['item'][i]);
				            			} 
				            		}
				            		break;
				            	case 3:
				            		var window_list = enianWindow.windowsList();
				            		for (var i in  window_list['item']) {
				            			enianWindow.close(window_list['item'][i]);
				            		}
				            		break;
				            }
						})
						return false;
					})

				 	if(obj.success){
				 		obj.success(layero,index)
				 	}
				 }
			})
		}
	
		//监听logo被单击
		enianAdmin.listen('btn-logo', function(obj) {
			enianAdmin.go('/index/index')
			menu_left.setCheck('title', "首页");
		})
		
		//监听更新主题
		enianAdmin.listen('updateTheme',function(name){
			$.ajax({
				type:"get",
				url:enianAdmin.config('path').theme + "/" + name + '.css',
				success:function(css){
					if(css){
						$('#THEME').html(css);
					}
				},
				async:true
			});
		})

		

		// 监听任务栏右键被点击
		$(".iframe-task").bind("contextmenu",function(){
			var arg = {};
			var menu_data=[
		            {'data':arg,'type':1,'title':'关闭所有窗口'}
		        ];
			
			mouseRightMenu.open(menu_data,{shade: [0.2, '#393D49']},function(active){
	            if(active.type==1){
	            	var window_list = enianWindow.windowsList();
            		for (var i in  window_list['item']) {
            			enianWindow.close(window_list['item'][i]);
            		}
	            }
			})
			return false;
		})

		
		
	}

	// 初始化方法
	function init(){
		evar = enianAdmin.evar={}; // 储存全局变量的对象，调用方式：varible.name

		// 表格高度
		evar.tableHeight = 'full-120'; 
	}
})